#include <functional>
#include <future>
#include <thread>
#include <utility>
#include <memory>

enum class  ThreadState{
    NotRun =0,
    Running,
    Finished
};

template<typename F,typename... Args>
class CThread{
public:
    using R = std::result_of<F(Args...)>::type; //返回值类型
    
    CThread(F&& fun,Args&&... args)
    {
        m_fun=std::bind(std::forward<F>(fun),std::forward<Args>(args)...);
        m_packageTask = make_shared<std::packaged_task<R()>>(m_fun); // 把函数入口及参数,打包(绑定)
		m_result = m_packageTask->get_future();

        m_thread = nullptr;
    }

    ~CThread()
    {
        Join();
        delete m_thread;
        m_thread = nullptr;
    }

    void Star()
    {
        m_thread=new std::thread([this]{
            state = ThreadState::Running;
            (*m_packageTask)();
            state = ThreadState::Finished;
        })
    }

    R GetResult()
    {
        return m_result.get();
    }

    ThreadState GetStatus()
    {
        return state;
    }

    void Join()
    {
        if(m_thread && m_thread->joinanble())
        {
            m_thread->join();
        }
    }


private:
    ThreadState state{ThreadState::NotRun};
    std::function<R()> m_fun;
    std::future<R> m_result; 
    std::shared_ptr<std::packaged_task<R()>> m_packageTask;
    std::thread* m_thread;
};